<?php

namespace app\api\controller\v43;

use app\aliyun\controller\AliyunFilterWordV2;
use app\api\controller\v2\Auth;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\chat\hz\HzHzQuestion;
use app\common\cachemodel\chat\hz\HzHzQuestionText;
use app\common\cachemodel\chat\HzChatLastSendTimeRecord;
use app\common\cachemodel\chat\HzChatRecord;
use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\cachemodel\chat\HzChatRecordDetailsReport;
use app\common\cachemodel\chat\HzChatRecordDetailsZan;
use app\common\cachemodel\chat\HzChatRecordDetailsZanData;
use app\common\cachemodel\chat\HzChatRecordDetailsZanData2;
use app\common\cachemodel\chat\HzDefaultReplyQuestion;
use app\common\lib\Util;
use app\common\lib\util\RecordTrain;
use app\common\model\Divination as DivinationAlias;
use app\common\model\Recode;
use app\common\service\ChatParse;
use think\Cache;
use think\Db;
use think\Log;
use think\response\Json;

class AiUserChat extends Auth
{
    /**
     * 获取对话记录列表
     */
    public function getChatIdList()
    {
        $hzChatRecordModel = new HzChatRecord();
        $pageData = $hzChatRecordModel->getListPage($this->user['id'], 'update_time', [], 0, 'desc', 0);

        $pageData['data'] = $hzChatRecordModel->pageDataResert($pageData['data']);

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 删除对话记录
     */
    public function delChatId()
    {
        $rid = input('rid/d', -1);
        if ($rid === -1)
        {
            return show(config('code.error'), '服务异常，档案不存在');
        }
        if ($rid === 0 && $this->user['rid'])
        {
            return show(config('code.error'), '服务异常，档案不存在');
        }
        $hzChatRecordModel = new HzChatRecord();

        if ($rid)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '服务异常，档案不存在');
            }
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {   // 没有自己的档案
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }
        if (!$chatId)
        {
            return show(config('code.success'), '会话记录已删除');
        }
        $res = $hzChatRecordModel->delChat($this->user['id'], $rid, $chatId);
        if ($res)
        {
            if ($rid === $this->user['rid'])
            {   // 删除用户自己的会话
                (new HzChatLastSendTimeRecord())->UpdateData($this->user['id'], ['chat_id' => 0]);
            }
            return show(config('code.success'), '操作成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 发送对话
     */
    public function sendQuestion()
    {
        $rid = input('rid/d', 0);
        $question = input('question/s', '');
        $gptModel = input('model/s', '');   // 会话模型
        $isRecommend = input('is_recommend/d', 0);   // 会话模型
        $isCall = input('is_call/d', 0);
        if (Util::commentCheck($this->user['id'], ['action' => 'sendQuestion', 'question' => $question, 'rid' => $rid], 5) && (int)$this->user['id'] != 10834769)
        {//mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        if (empty($question))
        {
            return show(config('code.error'), '请输入提问的内容');
        }
        if ($isCall)
        {
            if (mb_strlen($question) > 60)
            {
                return show(config('code.error'), '问题最多60字');
            }
        } else
        {
            if (mb_strlen($question) > 40)
            {
                return show(config('code.error'), '问题最多40字');
            }
        }
        if (!in_array($isCall, [0, 1], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        $aliRes = AliyunFilterWordV2::checkAIText($question);
        if ($aliRes['status'] === false)
        {
            return show(0, '检测到敏感内容');
        }
        $recodeInfo = null;
        if ($rid)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'] || $recodeInfo['status'] != 1)
            {
                return show(config('code.error'), '档案不存在');
            }
        } else
        {
            $rid = (int)($this->user['rid'] ?? 0);
        }

        $hzChatRecordModel = new HzChatRecord();
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $hzQuestionModel = new HzHzQuestion();

        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        if ($numData['res_num'] <= 0)
        {   // 会话次数 用尽
            return show(config('code.error'), '今日提问机会用尽，明天再来吧～');
        }
        // 是否是付费用户 是vip 或者 有付费次数 或者 有 赠送次数
        $isPayingUser = $numData['vip_level'] > 0 || $numData['pay_num'] > 0 || $numData['admin_num'] > 0;
        if (!$isPayingUser && $hzChatRecordDetailsModel->getIsFullLoad())
        {   // 不是付费用户
            return show(config('code.error'), '当前体验人数过多，请稍后重试～');
        }
        // 通过rid 取当前会话ID
        if ($rid)
        {
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }
        if (!$chatId)
        {
            return show(config('code.error'), '服务异常，请刷新页面重试～');
        }
        // 有档案情况
        if ($rid && !$recodeInfo)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
        }

        if (Util::isOnline())
        {   // 线上环境
            $chatConfig = (new AppConfig())->configInfo('chat_config');
            $gptModel = $chatConfig['gpt_model_name'] ?? '';
        }
        $chatData = $hzChatRecordModel->getInfoById($chatId);
        if (isset($chatData['rid2']) && $chatData['rid2'])
        {
            $recodeInfo2 = (new Recode())->getRecode(['id' => $chatData['rid2']]);
        }
        // 去 解析 输入内容的结果
        $queryResult = ChatParse::getQuestionParse($question, $recodeInfo, $chatId, $gptModel, $isRecommend, $recodeInfo2 ?? null, $isCall);
        // 旧版本返回格式【小于2.10.4】 {"success":true,"data":{"code":200,"message":"\u6210\u529f","data":{"type":2,"response":{"id":"","standsentence":"","constellation":""},"topsentence":[],"answer":"","default_answer_id":-1,"model_name":"ChatGLM-6b-LoRa-V10","semantic_answer_scene":0,"semantic_answer_cls_tools":[1,0,"afa109e1-4058-4f58-9158-cde151ab0a43",7,0,[]],"recommend_type":1,"city_type":0,"is_current_session_valid":1,"is_show_need_record_hint":0,"stream":1},"use_time":""},"question":"\u6211\u4eec\u4f1a\u5728\u4e00\u8d77\u5417"}
        if ($queryResult['success'])
        {
            if ($queryResult['data']['code'] === 200)
            {   // 语义解析成功
                $queryResult['data']['data']['use_time'] = $queryResult['data']['use_time'];
                $result = $queryResult['data']['data'];
            } else
            {   // 解析失败
                $this->setQueryLog($chatId, 0, $queryResult);

                if (isset($queryResult['data']['data']['type']) && $queryResult['data']['data']['type'] == 4)
                {
                    return show(202, '包含违规内容，请修改');
                }
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
        } else
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . "()  Curl请求python语义解析异常：errorCode:{$queryResult['errorCode']} ;errorMessage:{$queryResult['errorMessage']}", 'error', true);
            $this->setQueryLog($chatId, 0, $queryResult);
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        $nowTimw = $this->request->time();
        $insertData = [
            [   // 用户提问消息
                'chat_id' => $chatId,
                'uid' => $this->user['id'],
                'rid' => $rid,
                'type' => 2,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => $question, // 提问问题
                'data_type' => 1,
                'extend' => ['is_call' => $isCall, 'call_text_type' => 0],  // call_text_type = 0 表示 随机内容 非固定文案
                'result_data' => '',
                'option_id' => '',
                'pid' => 0,
                'create_time' => $nowTimw,
            ],
        ];
        if (isset($queryResult['history']) && $queryResult['history'] && isset($result['science_dice']) && $result['science_dice'] === 1)
        {   // 强制 开始 骰子
            $historyData = $queryResult['history'][count($queryResult['history']) - 1];
            // 获取 骰子问题
            $diceQuestion = $historyData['question'];
            // 扣除次数
            $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData);
            $_arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 16];// 行星id随机数种子`
            $insertData[] = [
                'chat_id' => $chatId,
                'uid' => $this->user['id'],
                'rid' => $rid,
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '', // 提问问题
                'data_type' => 3,   // 1=>普通消息  2=>结果消息 3=>扩展消息'
                'extend' => [
                    'result_type' => 2,
                    'model_name' => $gptModel,
                    'is_valid' => 1,
                    'stream' => 1,
                    'sas' => 3, // 语义解析集群分类场景结果 0为专业场景，1为基础场景，2为拒答场景 3未进行语义解析之间进行骰子获取结果
                    'sact' => [],
                    'dice_info' => [
                        'question' => $diceQuestion,
                        'planet' => $_arr[rand(0, count($_arr) - 1)],
                        'sign' => rand(1, 12),
                        'house' => rand(1, 12),
                        'id' => 0,
                        'answer_type' => 2,
                        'answer_content' => '',
                    ],
                ],
                'result_data' => '',
                'option_id' => '',
                'num_type' => $numData['use_type'], // 使用类型 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                'pid' => 0, // 待更新
                'create_time' => $nowTimw,
            ];
            $stream = 1;
        } else
        {
            $recommendGood = null;
            if (isset($result['recommend_type']) && $result['recommend_type'] > 0)
            {
                $recommendGood = [
                    'recommend_type' => $result['recommend_type'],
                    'city_type' => $result['city_type'],
                ];
                if ($result['recommend_type'] === 2)
                {
                    $recommendGood['question'] = $question;
                } elseif ($result['recommend_type'] === 6)
                {
                    $recommendGood['question_recommand'] = $result['question_recommand'] ?? [];
                }

                if ($result['stream'])
                {   // 新插件格式 字段不存在 为0
                    $recommendGood['style_type'] = 1;
                }
            }
            // 是否 有效【收费】
            $isValid = isset($result['is_current_session_valid']) && $result['is_current_session_valid'] === 1 ? 1 : 0;
            if ($isValid && $result['type'] === 2 && isset($result['is_combining']) && $result['is_combining'] === 1 && (!isset($chatData['rid2']) || !$chatData['rid2']))
            {
                $isValid = 0;
            }
            // 扣除 提问 次数
            if ($isValid)
            {   // 会话次数 -1
                $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData);
            }
            $stream = $result['stream'];
            switch ($result['type'])
            {
                case 0: // 命中
                    if ($rid)
                    {
                        // 通过命中条件 获取命中结果答案
                        $resultTextData = ChatParse::getAnalysisResult2($result['response']['id'], $result['response']['constellation'], $recodeInfo);
                        $insertData[] = [   // 用户提问消息
                            'chat_id' => $chatId,
                            'uid' => $this->user['id'],
                            'rid' => $rid,
                            'type' => 1,    //  1=>APP消息 2=>用户发送消息
                            'title' => '',
                            'content' => '', // 提问问题
                            'data_type' => 2,
                            'extend' => ['result' => $result['response'], 'result_type' => 0, 'model_name' => $result['model_name'] ?? '', 'recommend_good' => $recommendGood, 'is_valid' => $isValid, 'stream' => $result['stream'], 'is_call' => $isCall, 'call_text_type' => 0],
                            'result_data' => $resultTextData,
                            'num_type' => $isValid ? $numData['use_type'] : 0, // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                            'option_id' => '',
                            'pid' => 0, // 待更新
                            'create_time' => $nowTimw,
                        ];
                    } else
                    {   // 无档案情况 提示用户添加档案
                        $insertData[] = [   // 用户提问消息
                            'chat_id' => $chatId,
                            'uid' => $this->user['id'],
                            'rid' => $rid,
                            'type' => 1,    //  1=>APP消息 2=>用户发送消息
                            'title' => '',
                            'content' => '你需要告诉我你的档案，我才能帮你分析问题喔～', // 提问问题
                            'data_type' => 3,
                            'extend' => ['add_recode' => 1, 'model_name' => $result['model_name'] ?? '', 'is_valid' => 0, 'is_call' => $isCall, 'call_text_type' => 0],
                            'result_data' => '',
                            'option_id' => '',
                            'pid' => 0, // 待更新
                            'create_time' => $nowTimw,
                        ];
                    }
                    break;
                case 1: // 澄清
                    if (!$rid)
                    {   // 档案不存在
                        // 判定澄清选项是否需要档案
                        $qids = array_column($result['topsentence'], 'id');
                        $questionInfos = $hzQuestionModel->batchGetInfoByIds($qids);
                        foreach ($questionInfos as $questionInfoItem)
                        {
                            if ($questionInfoItem['need_recode'] === 1)
                            {   // 需要档案
                                $insertData[] = [   // 用户提问消息
                                    'chat_id' => $chatId,
                                    'uid' => $this->user['id'],
                                    'rid' => $rid,
                                    'type' => 1,    //  1=>APP消息 2=>用户发送消息
                                    'title' => '',
                                    'content' => '你需要告诉我你的档案，我才能帮你分析问题喔～', // 提问问题
                                    'data_type' => 3,
                                    'extend' => ['add_recode' => 1, 'result_type' => 1, 'model_name' => $result['model_name'] ?? '', 'is_valid' => 0, 'is_call' => $isCall, 'call_text_type' => 0],
                                    'result_data' => '',
                                    'option_id' => '',
                                    'pid' => 0, // 待更新
                                    'create_time' => $nowTimw,
                                ];
                                break;
                            }
                        }
                        break;
                    }
                    $insertData[] = [   // 用户提问消息
                        'chat_id' => $chatId,
                        'uid' => $this->user['id'],
                        'rid' => $rid,
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => '你要问的是这个问题吗？', // 提问问题
                        'data_type' => 3,   // 1=>普通消息  2=>结果消息 3=>扩展消息'
                        'extend' => ['sentence_option' => $result['topsentence'], 'model_name' => $result['model_name'] ?? '', 'recommend_good' => $recommendGood, 'is_valid' => $isValid, 'stream' => $result['stream'], 'is_call' => $isCall, 'call_text_type' => 0],  //  澄清数据
                        'result_data' => '',
                        'num_type' => $isValid ? $numData['use_type'] : 0, // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                        'option_id' => '',
                        'pid' => 0, // 待更新
                        'create_time' => $nowTimw,
                    ];
                    break;
                case 2: // 闲聊
                    $data_type = 1;
                    $extend = [
                        'result_type' => 2,
                        'model_name' => $result['model_name'] ?? '',
                        'recommend_good' => $recommendGood,
                        'is_valid' => $isValid,
                        'stream' => $result['stream'],
                        'is_call' => $isCall,
                        'call_text_type' => 0,
                    ];
                    if (isset($result['is_show_need_record_hint']) && (int)$result['is_show_need_record_hint'] === 1)
                    {   //如果python返回需要提示用户添加档案的话，返回数据的数据格式是添加档案
                        $data_type = 3;
                        $extend = ['add_recode' => 1, 'model_name' => $result['model_name'] ?? '', 'is_valid' => 0, 'is_call' => $isCall, 'call_text_type' => 0];
                    } else
                    {
                        $extend['sas'] = $result['semantic_answer_scene'];    // semantic_answer_scene   语义解析集群分类场景结果 当stream为1，并且回调流式接口才会返回 示例 0=>专业，1=>基础，2=>拒答
                        $extend['sact'] = $result['semantic_answer_cls_tools'];   // semantic_answer_cls_tools   语义解析集群分类工具结果 当stream为1，并且回调流式接口才会返回 示例 [0,0] 第一个元素为api_bot接口返回的recommend_type值，第2个元素为api_bot接口返回的city_type值

                        // 0=>人称对齐  1=>主档案未对齐    2=>副档案未对齐 【未对齐时不消耗次数】
                        $isCombiningClear = (int)($result['is_combining_clear'] ?? 0);
                        if (isset($result['is_combining']) && $result['is_combining'] === 1)
                        {   // 合盘情况
                            if (isset($chatData['rid2']) && $chatData['rid2'])
                            {   // 直接进行合盘
                                $recodeInfo2 = (new Recode())->getRecode(['id' => $chatData['rid2']]);
                                if ($isCombiningClear === 0)
                                {   // 人称对齐 进行 合盘
                                    $extend['synastry_result'] = [
                                        'rid' => $rid,
                                        'rname1' => $recodeInfo['name'],
                                        'rid2' => $chatData['rid2'],
                                        'rname2' => $recodeInfo2['name'],
                                        'question' => $question,
                                    ];
                                } else
                                {   // 推荐 合盘 澄清插件
                                    $data_type = 3;
                                    $extend['recommend_synastry'] = [
                                        'rid2' => $chatData['rid2'],
                                        'status' => 0,  // 0=>等待用户是否合盘 1=>合盘选择成功 2=>暂不合盘继续解答
                                        'avatar1' => $recodeInfo['avatar'],
                                        'avatar2' => $recodeInfo2['avatar'],
                                        'name1' => $recodeInfo['name'],
                                        'name2' => $recodeInfo2['name'],
                                        // 'not_combining_has_answer' => $result['not_combining_has_answer'],  // 选择暂不合盘时，0=>没有流式答案，只推荐插件功能【不记次数】   1=>通过流式获取答案，可能推荐其他插件【记次数】
                                        'is_combining_clear' => $isCombiningClear, // 对齐   1=>主档案未对齐    2=>副档案未对齐 【未对齐时不消耗次数】
                                        'type' => 2,    // 插件模式 1=>单盘情况  2=>合盘情况
                                    ];
                                    $extend['stream'] = 0;
                                    $isValid = 0;
                                    $stream = 0;
                                }
                            } else
                            {   // 推荐 合盘 插件  本次不扣次数
                                $data_type = 3;
                                $extend['recommend_synastry'] = [
                                    'rid2' => 0,
                                    'status' => 0,  // 0=>等待用户是否合盘 1=>合盘选择成功 2=>暂不合盘继续解答
                                    'avatar1' => $recodeInfo['avatar'],
                                    'name1' => $recodeInfo['name'],
                                    'not_combining_has_answer' => $result['not_combining_has_answer'],  // 选择暂不合盘时，0=>没有流式答案，只推荐插件功能【不记次数】   1=>通过流式获取答案，可能推荐其他插件【记次数】
                                    // 'is_combining_clear' => $isCombiningClear, // 对齐   1=>主档案未对齐    2=>副档案未对齐 【未对齐时不消耗次数】
                                    'type' => 1,    // 插件模式 1=>单盘情况  2=>合盘情况
                                ];
                                $extend['stream'] = 0;
                                $isValid = 0;
                                $stream = 0;
                            }
                        } else
                        {   // 单盘情况
                            if ($isCombiningClear && isset($chatData['rid2']) && $chatData['rid2'])
                            {   // 档案 未对齐
                                if ($isCombiningClear === 2)
                                {   // 副档案 未对齐
                                    $recodeInfo2 = (new Recode())->getRecode(['id' => $chatData['rid2']]);
                                    $ridItem = $chatData['rid2'];
                                    $avatar = $recodeInfo2['avatar'];
                                    $name = $recodeInfo2['name'];
                                } else
                                {   // 主档案 未对齐
                                    $ridItem = $rid;
                                    $avatar = $recodeInfo['avatar'];
                                    $name = $recodeInfo['name'];
                                }

                                $data_type = 3;
                                $extend['recode_choose'] = [
                                    'rid' => $ridItem,
                                    'status' => 0,  // 0=>等待用户确认解答 1=>已解答 2=>未解答
                                    'avatar' => $avatar,
                                    'name' => $name,
                                    'is_combining_clear' => $isCombiningClear, // 对齐   1=>主档案未对齐    2=>副档案未对齐 【未对齐时不消耗次数】
                                ];
                                $extend['stream'] = 0;
                                $isValid = 0;
                                $stream = 0;
                            }
                        }
                    }

                    $insertData[] = [   // 用户提问消息
                        'chat_id' => $chatId,
                        'uid' => $this->user['id'],
                        'rid' => $rid,
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => $stream === 0 ? $result['answer'] : '', // 提问问题
                        'data_type' => $data_type,   // 1=>普通消息  2=>结果消息 3=>扩展消息
                        'extend' => $extend,  //  澄清数据
                        'result_data' => '',
                        'num_type' => $isValid ? $numData['use_type'] : 0, // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                        'option_id' => '',
                        'pid' => 0, // 待更新
                        'create_time' => $nowTimw,
                    ];
                    break;
                case 3: // 默认回复
                    $insertData[] = [   // 用户提问消息
                        'chat_id' => $chatId,
                        'uid' => $this->user['id'],
                        'rid' => $rid,
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => '', // 提问问题
                        'data_type' => 3,   // 1=>普通消息  2=>结果消息 3=>扩展消息'
                        'extend' => [
                            'default_answer_id' => (int)$result['default_answer_id'],
                            'result_type' => 3,
                            'model_name' => $result['model_name'] ?? '',
                            'recommend_good' => $recommendGood,
                            'is_valid' => $isValid,
                            'stream' => $result['stream'],
                            'is_call' => $isCall,
                            'call_text_type' => 0,
                        ],  //  澄清数据
                        'result_data' => '',
                        'num_type' => $isValid ? $numData['use_type'] : 0, // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                        'option_id' => '',
                        'pid' => 0, // 待更新
                        'create_time' => $nowTimw,
                    ];
                    break;
                default:
            }
        }
        $resData = $hzChatRecordDetailsModel->SaveData($chatId, $insertData);
        if ($resData)
        {   // 发送成功
            // 更新 用户 最后发送消息 时间
            (new HzChatLastSendTimeRecord())->UpdateData($this->user['id'], ['last_send_time' => $nowTimw]);

            $chatDetailId = $resData[0]['id'];
            $hzChatRecordModel->updateData($chatId, $this->user['id'], [
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $nowTimw,
            ]);
            $this->setQueryLog($chatId, $chatDetailId, $queryResult);
            unset($resData[0]); // 只返回答案信息
            $resData = $hzChatRecordDetailsModel->dataListResert($resData, true);

            if (isset($resData[0]))
            {
                if ($resData[0]['is_stream_reload'] === 1)
                {
                    $resData[0]['is_stream_reload'] = 0;
                    $resData[0]['content'] = '';
                }
                $resData[0]['create_time'] = '';
                $resData[0]['stream'] = $stream;
                $resData[0]['num'] = $numData['res_num'];
                $resData[0]['input_text'] = $hzChatRecordDetailsModel->getInputPlaceholder($numData);
            }
            return show(config('code.success'), '请求成功', $resData[0]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    public function getQuestionAnswerStream()
    {
        $rid = input('rid/d', 0);
        $chatDetailId = input('chat_id/d', 0);
        $gptModel = input('model/s', '');   // 会话模型
        if (Util::commentCheck($this->user['id'], ['action' => 'getQuestionAnswerStream', 'chat_id' => $chatDetailId, 'rid' => $rid], 5) && (int)$this->user['id'] != 12346744)
        {
            return '';
        }
        $recodeInfo = null;
        if ($rid)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'])
            {
                return '';
            }
        } else
        {
            $rid = (int)($this->user['rid'] ?? 0);
        }

        $hzChatRecordModel = new HzChatRecord();
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        // 通过rid 取当前会话ID
        if ($rid)
        {
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }
        if (!$chatId)
        {
            return '';
        }
        // 有档案情况
        if ($rid && !$recodeInfo)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
        }
        $chatData = $hzChatRecordModel->getInfoById($chatId);
        $rid2 = $chatData['rid2'] ?? 0;
        if (Util::isOnline())
        {   // 线上环境
            $chatConfig = (new AppConfig())->configInfo('chat_config');
            $gptModel = $chatConfig['gpt_model_name'] ?? '';
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小')
        {   // 安卓  并且 版本 低于2.10.6
            $chatDetailId += 1000000;
        }
        $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
        $isTarot = 0;
        if (isset($chatDetailInfo['extend']['dice_info']))
        {
            $isDice = 1;
            $planet = $chatDetailInfo['extend']['dice_info']['planet'] ?? 0;
            $sign = $chatDetailInfo['extend']['dice_info']['sign'] ?? 1;
            $house = $chatDetailInfo['extend']['dice_info']['house'] ?? 1;
            $planetName = (new Util())->PlanetTypeName($planet);
            $signConfig = config('astro.sign_name');

            $diceInfo = [
                'dice_planet' => $planetName,
                'dice_sign' => $signConfig[$sign],
                'dice_house' => $house . '宫',
            ];
            $question = $chatDetailInfo['extend']['dice_info']['question'] ?? '';
        } else if (isset($chatDetailInfo['extend']['tarot_info']))
        {
            $isTarot = 1;
            if ($chatDetailInfo['extend']['tarot_info']['status'] == 2)
            {
                echo '';
                exit;
            }
            $tarotConfig = config('tarot');
            $diceOrTarotInfo = [];
            $typeConfig = [
                1001 => 2,  // '恋爱圣三角',
                1002 => 3,  // '吉普赛十字牌阵',
                2001 => 1,  // '时间之剑',
                2002 => 4,  // '万能牌阵',
                3001 => 5,  // '每周运势牌阵',
                4001 => 6,  // '身心灵牌阵',
                4002 => 7,  // '四元素牌阵',
                4003 => 8,  // '六芒星牌阵',
                4004 => 9,  // '圣三角',
                5001 => 10, // '灵感对应牌阵',
                6001 => 11, // '抉择牌阵（2选1）',
                6002 => 12, // '抉择牌阵（3选1）',
            ];
            foreach ($chatDetailInfo['extend']['tarot_info']['tarot_cards'] as $cardItem)
            {
                $diceOrTarotInfo[] = $cardItem['name'];
            }

            if (count($diceOrTarotInfo) < count($tarotConfig['tarot_type'][$chatDetailInfo['extend']['tarot_info']['tarot_type']]))
            {
                $diceOrTarotInfo[] = '';
            }
            $tarotInfo = [
                'uid' => $this->user['id'],
                'dice_or_tarot_info' => $diceOrTarotInfo,
                'did' => 0,    // 记录ID
                'type' => $typeConfig[$chatDetailInfo['extend']['tarot_info']['tarot_type']],   // 牌阵类型  0=>骰子  1=>塔罗-时间之箭  2=>塔罗-恋爱圣三角  3=>塔罗-吉普赛十字牌阵  4=>塔罗-万能牌阵  5=>塔罗-每周运势牌阵  6=>塔罗-身心灵牌阵  7=>塔罗-四元素牌阵  8=>塔罗-六芒星牌阵  9=>塔罗-圣三角  10=>塔罗-灵感对应牌阵  11=>塔罗-抉择牌阵（2选1）  12=>塔罗-抉择牌阵（3选1）
                'query' => $chatDetailInfo['extend']['tarot_info']['question'],  // 问题
                'brand_index' => 0,    // 牌位
                // 'brand_index' => $aiAnswerInfo['location'] === -1 ? 0 : $aiAnswerInfo['location'],    // 牌位
            ];

        } elseif (isset($chatDetailInfo['extend']['synastry_result']))
        {
            $question = $chatDetailInfo['extend']['synastry_result']['question'] ?? '';
            $rid2 = $chatDetailInfo['extend']['synastry_result']['rid2'];
            $recodeInfo['name'] = $chatDetailInfo['extend']['synastry_result']['rname1'] ?? '';
            $rname2 = $chatDetailInfo['extend']['synastry_result']['rname2'] ?? '';
            $isCombining = 1;
        } elseif (isset($chatDetailInfo['extend']['recode_choose_result']))
        {
            $question = $chatDetailInfo['extend']['recode_choose_result']['question'] ?? '';
            $rid2 = 0;
            $recodeInfo = (new Recode())->getRecode(['id' => $chatDetailInfo['extend']['recode_choose_result']['rid']]);
        } else
        {
            $parentData = $hzChatRecordDetailsModel->getInfoById($chatDetailInfo['pid'], ['content', 'extend', 'pid']);
            if (isset($parentData['extend']['recommend_synastry']) && $parentData['pid'])
            {
                $parentData1 = $hzChatRecordDetailsModel->getInfoById($parentData['pid'], ['content']);
                $question = $parentData1['content'] ?? '';
            } else
            {
                $question = $parentData['content'] ?? '';
            }
        }
        if ($rid2 && !isset($rname2))
        {
            $recodeInfo2 = (new Recode())->getRecode(['id' => $rid2]);
            $rname2 = $recodeInfo2['name'] ?? '';
        }
        $isConsum = 0;
        if (isset($chatDetailInfo['num_type']) && $chatDetailInfo['num_type'])
        {
            if ($chatDetailInfo['num_type'] === 1)
            {   // 免费次数
                $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
                if ($numData['vip_level'] > 0 || $numData['pay_num'] > 0 || $numData['admin_num'] > 0)
                {
                    $isConsum = 1;
                }
            } else
            {   // 付费次数
                $isConsum = 1;
            }
        }
        $isCall = $chatDetailInfo['extend']['is_call'] ?? 0;

        if ($isTarot)
        {
            $queryStr = ChatParse::getTarotAiAnswerStreamData($tarotInfo);
        } else
        {
            // 去 解析 输入内容的结果
            $queryStr = ChatParse::getQuestionParseStreamData($question, $recodeInfo, $chatId, $chatDetailId, $gptModel, [
                'semantic_answer_scene' => $chatDetailInfo['extend']['sas'],
                'semantic_answer_cls_tools' => $chatDetailInfo['extend']['sact'],
                'is_dice' => $isDice ?? 0,
                'dice_info' => $diceInfo ?? null,
                'is_consum' => $isConsum,
                'rid1' => $rid2,
                'rid1_name' => $rname2 ?? '',
                'is_combining' => $isCombining ?? 0,
                'is_call' => $isCall,
            ]);
        }

        $chatDetailInfo['extend']['stream'] = 2;
        $queryStr = str_replace("￥", "", $queryStr);
        $answerViolation = false;
        if (strpos($queryStr, 'θ') !== false)
        {
            $answerViolation = true;
            $queryStr = '准准认为你的问题包含敏感信息，换个问题再试试吧。';
            $chatDetailInfo['extend']['answer_violation'] = 1;  // 答案违规
        }
        if (isset($isDice) && $isDice)
        {
            $chatDetailInfo['extend']['dice_info']['answer_content'] = $queryStr;
            if (!$answerViolation)
            {
                $queryStr = '';
            }
        }
        if ($isTarot)
        {
            $chatDetailInfo['extend']['tarot_info']['answer_content'] = $queryStr;
            if (!$answerViolation)
            {
                $queryStr = '';
            }
        }

        $upData = ['content' => $queryStr, 'extend' => json_encode($chatDetailInfo['extend'], JSON_UNESCAPED_UNICODE)];
        if ($answerViolation && isset($chatDetailInfo['num_type']) && $chatDetailInfo['num_type'])
        {   //问题违规  本次对话消耗次数 将次数还原
            $upData['num_type'] = 0;
            $hzChatRecordDetailsModel->chatQueryEndNumInc($this->user['id'], $chatDetailInfo['num_type']);
        }
        // 更新结果
        $hzChatRecordDetailsModel->UpdateData($chatDetailId, $upData);
    }

    /**
     * 记录 语义解析 日志
     * @param int $chatId
     * @param $chatDetailId
     * @param array $queryResult
     * @return void
     */
    public function setQueryLog(int $chatId, $chatDetailId, array $queryResult): void
    {
        Db::table('wechat_backup_07_18_14_43_00.hz_chat_python_result_log')->insert(['chat_id' => $chatId, 'chat_record_id' => $chatDetailId, 'result' => json_encode($queryResult, JSON_UNESCAPED_UNICODE), 'create_time' => time()]);
    }

    /**
     * 问题澄清
     */
    public function questionSentence()
    {
        $chatDetailId = input('chat_id/d', 0);
        $optionId = input('option_id/d', 0);
        $rid = input('rid/d', 0);

        if (!$chatDetailId)
        {
            return show(config('code.error'), '请求异常，请刷新重试～');
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小')
        {   // 安卓  并且 版本 低于2.10.6
            $chatDetailId += 1000000;
        }
        if (!$optionId)
        {
            return show(config('code.error'), '请求异常，请刷新重试～');
        }
        $recodeInfo = null;
        if ($rid)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '档案不存在');
            }
        } else
        {
            $rid = (int)($this->user['rid'] ?? 0);
        }

        $hzChatRecordModel = new HzChatRecord();
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $hzQuestionModel = new HzHzQuestion();
        // 通过rid 取当前会话ID
        if ($rid)
        {
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }
        if (!$chatId)
        {
            return show(config('code.error'), '服务异常，请刷新页面重试～');
        }

        $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);

        if ($chatId !== $chatDetailInfo['chat_id'] || $chatDetailInfo['option_id'])
        {
            return show(config('code.error'), '数据异常，请稍后重试～');
        }

        $optionInfo = array_column($chatDetailInfo['extend']['sentence_option'], null, 'id');

        if (!isset($optionInfo[$optionId]))
        {
            return show(config('code.error'), '服务异常，选项不存在～');
        }
        $nowTimw = time();
        $insertData = [];
        // 获取问题信息
        $questionInfo = $hzQuestionModel->getInfoById($optionId, ['id', 'question', 'need_recode']);
        if ($questionInfo['need_recode'] === 1)
        {
            if (!$rid)
            {
                $insertData[] = [   // 用户提问消息
                    'chat_id' => $chatId,
                    'uid' => $this->user['id'],
                    'rid' => $rid,
                    'type' => 1,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => '你需要告诉我你的档案，我才能帮你分析问题喔～', // 提问问题
                    'data_type' => 3,
                    'extend' => ['add_recode' => 1],
                    'result_data' => '',
                    'option_id' => '',
                    'pid' => 0, // 待更新
                    'create_time' => $nowTimw,
                ];
            } else
            {
                if (!$recodeInfo)
                {
                    $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
                }
            }
        } else
        {
            $recodeInfo = null;
        }
        if (empty($insertData))
        {
            // 澄清选项 取选项问题结果答案
            $resultTextData = ChatParse::getAnalysisResult2($optionId, $optionInfo[$optionId]['constellation'], $recodeInfo);
            $insertData[] = [   // 用户提问消息
                'chat_id' => $chatId,
                'uid' => $this->user['id'],
                'rid' => $rid,
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '', // 提问问题
                'data_type' => 2,
                'extend' => ['result' => $optionInfo[$optionId], 'result_type' => 0],
                'result_data' => $resultTextData,
                'option_id' => '',
                'pid' => $chatDetailId,
                'create_time' => $nowTimw,
            ];
        }
        // 更新选项
        $hzChatRecordDetailsModel->UpdateData($chatDetailId, [
            'option_id' => $chatDetailInfo['option_id'] ? $chatDetailInfo['option_id'] . ',' . $optionId : $optionId,
        ]);

        $resData = $hzChatRecordDetailsModel->SaveData($chatId, $insertData);
        $resData = $hzChatRecordDetailsModel->dataListResert($resData, true);
        if (isset($resData[0]))
        {
            $resData[0]['create_time'] = '';
        }
        return show(config('code.success'), '请求成功', $resData[0]);
    }

    public function zan()
    {
        $chatDetailId = input('chat_id/d', 0);
        $type = input('type/d', 0); // 1 点赞  2 踩
        $fid = input('fid/s', ''); // 反馈原因ID

        if (!in_array($type, [0, 1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!$chatDetailId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小')
        {   // 安卓  并且 版本 低于2.10.6
            $chatDetailId += 1000000;
        }
        //验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['action' => 'zan', 'chat_detail_id' => $chatDetailId, 'type' => $type, 'fid' => $fid]))
        {
            return show(config('code.error'), '别心急，等一等');
        }
        $fidArr = [];
        if ($type === 2 && $fid)
        {
            $fidArr = explode(',', $fid);
            $feedbackConfig = config('feedback.feedback_list');
            foreach ($fidArr as $fidItem)
            {
                if (!isset($feedbackConfig[$fidItem]))
                {
                    return show(config('code.error'), '反馈异常，请稍后再试～');
                }
            }
        }

        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
        if ($chatDetailInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $oldZan = $chatDetailInfo['extend']['zan'] ?? 0;
        if ($oldZan === $type)
        {
            return show(config('code.success'), '操作成功');
        }

        $updateData = [];
        if ($oldZan === 1)
        {
            $updateData['zan'] = Db::raw('zan - 1');
        }
        if ($oldZan === 2)
        {
            $updateData['zan1'] = Db::raw('zan1 - 1');
        }
        if ($type === 1)
        {
            $updateData['zan'] = Db::raw('zan + 1');
        }
        if ($type === 2)
        {
            $updateData['zan1'] = Db::raw('zan1 + 1');
        }

        $extend = $chatDetailInfo['extend'];
        $extend['zan'] = $type;
        // 更新 会话记录信息
        $hzChatRecordDetailsModel->UpdateData($chatDetailId, [
            'extend' => json_encode($extend, JSON_UNESCAPED_UNICODE),
        ]);
        $resFeedbackReason = $type === 2 ? $fid : '';
        // 更新 点赞信息
        (new HzChatRecordDetailsZan())->setZan($this->user['id'], $chatDetailId, $type, $resFeedbackReason);
        $pid = $chatDetailInfo['pid'];
        if ($chatDetailInfo['pid'])
        {
            $pData = $hzChatRecordDetailsModel->getInfoById($chatDetailInfo['pid']);
            if ($pData['type'] === 1)
            {
                $pid = $pData['pid'];
            }
        }
        $qid = 0;
        $questionType = 0;
        $isChitchat = false;    // 是否是闲聊
        if (isset($extend['result_type']))
        {   //  结果类型  0=>命中｜澄清命中   1=>澄清   2=>闲聊   3=>默认回复
            switch ($extend['result_type'])
            {
                case 0:
                    $qid = $extend['result']['id'];
                    $questionType = 1;
                    break;
                case 2:
                    $isChitchat = true;
                    break;
                case 3:
                    $qid = $extend['default_answer_id'];
                    $questionType = 2;
                    break;
                default:
            }
        }
        (new HzChatRecordDetailsZanData())->setZan($this->user['id'], $chatDetailId, $type, $fidArr, $pid, $questionType, $qid);

        if ($isChitchat)
        {   // 闲聊 记录 信息
            $recodeInfoStr = '';
            if ($chatDetailInfo['rid'])
            {
                $recodeInfo = (new Recode())->getRecode(['id' => $chatDetailInfo['rid']]);
                $recodeInfoStr = (new RecordTrain())->format($recodeInfo);
            }
            $questionInfo = $hzChatRecordDetailsModel->getInfoById($pid, ['content']);
            $zanData = [
                'uid' => $this->user['id'],
                'chat_detail_id' => $chatDetailId,
                'status' => $type,
                'feedback_ids' => $type === 2 ? $fid : '',
                'pid' => $pid,
                'question' => $questionInfo['content'],
                'replay' => $chatDetailInfo['content'],
                'recode_info' => $recodeInfoStr,
                'model_name' => $chatDetailInfo['extend']['model_name'] ?? '',
            ];
            (new HzChatRecordDetailsZanData2())->setZan($zanData);
        }

        if (isset($extend['result_type']))
        {
            switch ($extend['result_type'])
            {
                case 0: // 结果类型  0=>命中｜澄清命中   1=>澄清   2=>闲聊   3=>默认回复
                    if (isset($extend['result']['id']))
                    {
                        // 更新 问题信息 点赞
                        (new HzHzQuestion())->where('id', $extend['result']['id'])->update($updateData);
                        // 更新 词条 点赞信息
                        foreach ($chatDetailInfo['result_data'] as $textId)
                        {
                            (new HzHzQuestionText())->where('id', $textId)->update($updateData);
                        }
                    }
                    break;
                case 3:
                    if (isset($extend['default_answer_id']))
                    {
                        (new HzDefaultReplyQuestion())->where('id', $extend['default_answer_id'])->update($updateData);
                    }
                    break;
                default:

            }
        }

        return show(config('code.success'), '操作成功');
    }

    /**
     * 占卜
     * @return Json
     */
    public function divinationStart()
    {
        $data['question'] = htmlspecialchars(trim(input('question/s', '')));
        if (mb_strlen($data['question']) === 0)
        {
            return show(config('code.error'), '请输入问题，再进行提问');
        };
        $data['uid'] = $this->user['id'];
        $data['timezone'] = input('timezone');// 时区
        $data['longitude'] = input('longitude');// 经度
        $data['latitude'] = input('latitude');// 纬度
        $data['tag_id'] = $paramsMap['tag_id'] ?? input('tag_id/d', 0);// 指定类型
        $chatDetailId = input('chat_id/d', 0);// 纬度
        if (Util::commentCheck($this->user['id'], ['action' => 'divinationStart', 'question' => $data['question'], 'timezone' => $data['timezone'], 'longitude' => $data['longitude'], 'latitude' => $data['latitude'], 'chat_id' => $chatDetailId], 2))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小')
        {   // 安卓  并且 版本 低于2.10.6
            $chatDetailId += 1000000;
        }
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        if ($chatDetailId)
        {
            $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
            if (!$chatDetailInfo || $chatDetailInfo['uid'] !== $this->user['id'] || !isset($chatDetailInfo['extend']['recommend_good']['recommend_type']) || $chatDetailInfo['extend']['recommend_good']['recommend_type'] !== 2 || isset($chatDetailInfo['extend']['recommend_good']['btn_is_hidden']))
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
        }
        // 安卓端在塔罗开发版本时，纬度和时区字段两个值传反了，特殊处理
        $_arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 16];// 行星id随机数种子`
        $data['planet'] = $_arr[rand(0, count($_arr) - 1)];
        $data['sign'] = rand(1, 12);
        $data['house'] = rand(1, 12);
        $data['deg'] = round(randomFloat(0, 29), 8);
        $data['create_time'] = time();

        try
        {
            $chatConfig = (new AppConfig())->configInfo('chat_config');
            // 剩余 会话 次数
            $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);    //  剩余对话次数
            if (isset($chatConfig['dice_use_ali_model']) && $chatConfig['dice_use_ali_model'] == 1 && isset($chatDetailInfo) && $chatDetailInfo)
            {   // 使用 阿里 模型 并且 当前为 对话占卜情况
                $chatDetailInfo['extend']['recommend_good']['btn_is_hidden'] = 1;
                if ($numData['res_num'] < 1)
                {   // 次数 太少
                    return show(config('code.error'), '骰子解答需要消耗对话次数，请购买。');
                }
                // 扣除次数
                $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData);
                // 更新 占卜信息
                $hzChatRecordDetailsModel->UpdateData($chatDetailId, [
                    'extend' => json_encode($chatDetailInfo['extend'], JSON_UNESCAPED_UNICODE),
                ]);
                $extend = $chatDetailInfo['extend'];
                unset($extend['recommend_good']);
                unset($extend['synastry_result']);
                $extend['dice_info'] = [
                    'question' => $chatDetailInfo['extend']['recommend_good']['question'],
                    'planet' => $data['planet'],
                    'sign' => $data['sign'],
                    'house' => $data['house'],
                    'id' => 0,
                    'answer_type' => 2,
                    'answer_content' => '',
                ];
                $extend['is_valid'] = 1;
                $extend['stream'] = 1;
                $chatInfo = (new HzChatRecord())->getInfoById($chatDetailInfo['chat_id'], ['rid']);
                $insertData = [   // 用户提问消息
                    [
                        'chat_id' => $chatDetailInfo['chat_id'],
                        'uid' => $this->user['id'],
                        'rid' => $chatInfo['rid'] ?? $chatDetailInfo['rid'],
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => '', // 提问问题
                        'data_type' => 3,   // 1=>普通消息  2=>结果消息 3=>扩展消息'
                        'extend' => $extend,  //  澄清数据
                        'result_data' => '',
                        'option_id' => '',
                        'num_type' => $numData['use_type'], // 使用类型 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                        'pid' => $chatDetailId, // 待更新
                        'create_time' => $this->request->time(),
                    ],
                ];
                $resInsertData = $hzChatRecordDetailsModel->SaveData($chatDetailInfo['chat_id'], $insertData);
                array_unshift($resInsertData, $chatDetailInfo);
                $resData = $hzChatRecordDetailsModel->dataListResert($resInsertData, true);
                $resData[0]['stream'] = 0;
                $resData[1]['create_time'] = '';
                $resData[1]['stream'] = 1;
                $resData[1]['is_stream_reload'] = 0;

                return show(config('code.success'), '请求成功', [
                    'num' => $numData['res_num'],
                    'input_text' => $hzChatRecordDetailsModel->getInputPlaceholder($numData),
                    'list' => $resData,
                ]);
            } else
            {
                $validate = validate('DivinationIndex');
                if ($validate->check($data) !== true)
                {
                    Log::write('提问错误:' . $validate->getError(), 'error_divination', true);
                    return show(config('code.error'), (string)$validate->getError());
                }
                $id = DivinationAlias::insertGetId($data);
                Cache::rm(DivinationAlias::REDIS_KEY_IDS . $data['uid']);
                if (isset($chatDetailInfo) && $chatDetailInfo)
                {
                    $extend = $chatDetailInfo['extend'];
                    $extend['dice_info'] = [
                        'question' => $extend['recommend_good']['question'],
                        'planet' => $data['planet'],
                        'sign' => $data['sign'],
                        'house' => $data['house'],
                        'id' => (int)$id,
                        'answer_type' => 1,
                    ];
                    unset($extend['recommend_good']);
                    // 更新 占卜信息
                    $hzChatRecordDetailsModel->UpdateData($chatDetailId, [
                        'extend' => json_encode($extend, JSON_UNESCAPED_UNICODE),
                    ]);
                    $chatDetailInfo['extend'] = $extend;
                    $resData = $hzChatRecordDetailsModel->dataListResert([$chatDetailInfo], true);
                    $resData[0]['create_time'] = '';
                    $resData[0]['stream'] = 0;

                    return show(config('code.success'), '请求成功', [
                        'num' => $numData['res_num'],
                        'input_text' => $hzChatRecordDetailsModel->getInputPlaceholder($numData),
                        'list' => $resData,
                    ]);
                }
            }
        }
        catch (\Exception $e)
        {
            Log::write('提问入库失败:' . $e->getMessage(), 'divination_error', true);
            return show(config('code.error'), '请稍后重试');
        }

        return show(config('code.success'), '加载成功', ['did' => (int)$id, 'time' => $data['create_time']]);
    }

    /**
     * 举报
     */
    public function report()
    {
        $chatDetailId = input('chat_id/d', 0);
        $reason = input('reason/s', '');

        if (!$chatDetailId || (!$reason && $reason !== "0"))
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小')
        {   // 安卓  并且 版本 低于2.10.6
            $chatDetailId += 1000000;
        }
        //验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['action' => 'report', 'chat_detail_id' => $chatDetailId, 'reason' => $reason,]))
        {
            return show(config('code.error'), '别心急，等一等');
        }

        $reasonArr = explode(',', $reason);
        foreach ($reasonArr as $rid)
        {
            /**
             * 举报原因
             * 0 => 存在广告营销信息
             * 1 => 涉嫌黄、赌、毒等违规内容
             * 2 => 侵害他人权益及隐私
             * 3 => 不良传导，价值观扭曲
             * 4 => 传播不实信息，内容失实
             * 5 => 其他原因
             */

            if (!in_array($rid, [0, 1, 2, 3, 4, 5]))
            {
                return show(config('code.error'), '请求异常，请稍后再试');
            }
        }

        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
        if ($chatDetailInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        (new HzChatRecordDetailsReport())->setReport($this->user['id'], $chatDetailId, $reason, 1);

        return show(config('code.success'), '举报成功');
    }
}
